package com.example.springactiviti.controller;

import com.example.springactiviti.vo.Res;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/development")
public class DevelopmentController {

    @Autowired
    RepositoryService repositoryService;
    @Autowired
    RuntimeService runtimeService;
    @Autowired
    TaskService taskService;

    @RequestMapping("/upload")
    @ResponseBody
    public Res<String> upload(MultipartFile file) throws IOException {
        Deployment deployment = repositoryService.createDeployment().addInputStream(file.getOriginalFilename(), file.getInputStream()).deploy();
        return Res.success(deployment.getId());
    }
    @RequestMapping("/create")
    @ResponseBody
    public Res<String> create(String defKey, Map<String,Object> params){
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(defKey,params);
        return Res.success(processInstance.getId());
    }

    @RequestMapping("/queryUserTask")
    @ResponseBody
    public Res queryUserTask(String userName){
        List<Task> tasks= taskService.createTaskQuery().taskCandidateOrAssigned(userName).list();
        List<Map<String,Object>> resultList = new ArrayList<>();
        for (Task task : tasks) {
            Map<String,Object> map = new HashMap<>();
            map.put("taskId",task.getId());
            map.put("taskName",task.getName());
            resultList.add(map);
        }
        return Res.success(resultList);
    }
    @RequestMapping("/completeTask")
    @ResponseBody
    public Res completeTask(String taskId,@RequestParam Map<String,Object> params){
        taskService.complete(taskId,params);
        return Res.success();
    }



}
